//
//  TUIBaseChatViewController.m
//  UIKit
//
//  Created by annidyfeng on 2019/5/21.
//

#import "TUIBaseChatViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "ReactiveObjC/ReactiveObjC.h"
#import "TUIBaseMessageController.h"
#import "TUIImageMessageCellData.h"
#import "TUIVideoMessageCellData.h"
#import "TUIFileMessageCellData.h"
#import "TUIVoiceMessageCellData.h"
#import "TUITextMessageCellData.h"
#import "TUIReplyMessageCellData.h"
#import "TUIDefine.h"
#import "TUIMessageMultiChooseView.h"
#import "TUIMessageController.h"
#import "TUIChatDataProvider.h"
#import "TUIMessageDataProvider.h"
#import "TUICameraViewController.h"
#import "TUITool.h"
#import "TUICore.h"
#import "TUIDefine.h"
#import "NSDictionary+TUISafe.h"
#import "NSString+TUIEmoji.h"
#import "TUIThemeManager.h"
#import "TUIChatMediaDataProvider.h"
#import "TUIMessageReadViewController.h"
#import "TUIJoinGroupMessageCell.h"
#import "TUICloudCustomDataTypeCenter.h"
#import "TUILogin.h"
#import "TUIChatConfig.h"
#import "TUIChatModifyMessageHelper.h"
#import "TUIAIDenoiseSignatureManager.h"
#import "NSString+TUIEmoji.h"
#import "TUIPollContainerCellData.h"
#import "TUIGroupNoteContainerCellData.h"
//历史聊天记录
#import "LGConsultHistoryController.h"
//医生详情
#import "LGPersionalDataController.h"
//患者详情
#import "LGPatientDetailController_YHJK.h"//癌症
#import "LGPatientDetailController2.h"
//患者病情概览
#import "LGDiseaseOverviewController.h"
//群聊成员
#import "LGGroupChatMemberController.h"
//开具医嘱
#import "LGAddDoctorAdviceController.h"
//随访及医嘱记录
#import "LGFollowAdviceRecordController.h"
//推荐医生
#import "LGRecommendDoctorController.h"
//推荐服务
#import "LGRecommendServiceController.h"
#import "LGServiceDetailController.h"
//发送评估列表
#import "LGSendEvaluationController.h"
//订单详情
#import "LGOrderDetailController.h"
//自定义导航头
#import "LGChatPatientNavigation.h"
#import "LGChatTeamNavigation.h"

//患者被删除
#import "LGPatientDeleteView.h"
//接诊、拒诊
#import "LGReceptionView.h"
//延长问诊
#import "LGExtendTimeView.h"


#define viewWidth  self.view.frame.size.width
#define viewHeight  self.view.frame.size.height

static  CGFloat topMargin;

@interface TUIBaseChatViewController () <TUIBaseMessageControllerDelegate,
                                         TUIInputControllerDelegate,
                                         UIImagePickerControllerDelegate,
                                         UIDocumentPickerDelegate,
                                         UINavigationControllerDelegate,
                                         TUIMessageMultiChooseViewDelegate,
                                         TUIChatBaseDataProviderForwardDelegate,
                                         TUINotificationProtocol,
                                         TUIJoinGroupMessageCellDelegate,
                                         V2TIMConversationListener,
                                         TUINavigationControllerDelegate,
                                         TUIChatMediaDataListener,LGExtendTimeViewDelegate>
/**   */
@property (nonatomic , strong)LGChatPatientNavigation *patientNavigation;
/**   */
@property (nonatomic , strong)LGChatTeamNavigation *teamNavigation;
/**  患者被删除 */
@property (nonatomic , strong)LGPatientDeleteView *deleteView;
/**  接诊、拒诊 */
@property (nonatomic , strong)LGReceptionView *receptView;
/**   */
@property (nonatomic , strong)UIImageView *extendTimeView;
/**   */
@property (nonatomic , strong)LGExtendTimeView *timeView;

@property (nonatomic, strong) TUIMessageMultiChooseView *multiChooseView;
@property (nonatomic, assign) BOOL responseKeyboard;
// @{@"serviceID" : serviceID, @"title" : @"Video call", @"image" : image}
@property (nonatomic, strong) NSMutableArray<NSDictionary *> *resgisterParam;
@property (nonatomic, strong) TUIChatDataProvider *dataProvider;

@property (nonatomic, weak) UIViewController *forwardConversationSelectVC;
@property (nonatomic) NSArray<TUIMessageCellData *> *forwardSelectUIMsgs;
@property (nonatomic) BOOL isMergeForward;

@property (nonatomic, copy) NSString *translatedText;

@property (nonatomic, strong) TUIChatMediaDataProvider *mediaProvider;

@property (nonatomic, assign) BOOL needScrollToBottom;

@property (nonatomic, assign) BOOL firstAppear;
/**   */
@property (nonatomic , strong)NSDictionary *customDic;
/**   */
@property (nonatomic , copy)NSString *patientid;
/**   */
@property (nonatomic , assign)NSInteger seconds;
/**   */
@property (nonatomic , strong)NSTimer *timer;
/**   */
@property (nonatomic , assign)BOOL canCall;
/**   */
@property (nonatomic , assign)BOOL isfirst;

@end

@implementation TUIBaseChatViewController

#pragma mark - Life Cycle
- (instancetype)init {
    self = [super init];
    if (self) {
        [TUIBaseChatViewController createCachePath];
        [[TUIAIDenoiseSignatureManager sharedInstance] updateSignature];
        [TUIConfig defaultConfig].avatarType = TAvatarTypeRadiusCorner;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isfirst = YES;
    self.canCall = YES;
    self.firstAppear = YES;
    self.fd_prefersNavigationBarHidden = YES;
    topMargin = (_appointment_id && _appointment_id.length>0 && ![_appointment_id containsString:@"999999999-"])?(topBarHeight+viewPix(44)):topBarHeight;
    self.view.backgroundColor = TUICoreDynamicColor(@"controller_bg_color", @"#EDEDED");
    self.edgesForExtendedLayout = UIRectEdgeNone;
    //设置通知监听
    [self configNotification];
    //创建聊天控制器
    [self createMessageController];
    [self createSubView];
    //初始化接口
    [self requestAppointData];
}

- (void)willMoveToParentViewController:(UIViewController *)parent {
    if (parent == nil) {
        [self saveDraftContent];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    self.responseKeyboard = YES;
    if (self.firstAppear) {
        [self loadDraftContent];
        self.firstAppear = NO;
    }
    
    if (self.needScrollToBottom) {
        [self.messageController scrollToBottom:YES];
        self.needScrollToBottom = NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.responseKeyboard = NO;
    [self openMultiChooseBoard:NO];
    [self.messageController enableMultiSelectedMode:NO];
    //消息已读上报
    [self.messageController readReport];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    if (self.inputController.status == Input_Status_Input ||
        self.inputController.status == Input_Status_Input_Keyboard) {
        CGPoint offset = self.messageController.tableView.contentOffset;
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            __strong typeof(weakSelf)strongSelf = weakSelf;
            strongSelf.responseKeyboard = YES;
            [UIApplication.sharedApplication.keyWindow endEditing:YES];
            [strongSelf inputController:strongSelf.inputController didChangeHeight:CGRectGetMaxY(strongSelf.inputController.inputBar.frame) + Bottom_SafeHeight];
            [strongSelf.messageController.tableView setContentOffset:offset];
        });
    }
}

//添加扩展按钮：视频通话、慢病服务、推荐医生。。。
- (void)setConversationData:(TUIChatConversationModel *)conversationData{
    _conversationData = conversationData;
    self.resgisterParam = [NSMutableArray array];
    _moreMenus = ({
//        NSMutableArray<TUIInputMoreCellData *> *moreMenus = [TUIChatDataProvider moreMenuCellDataArray:conversationData.groupID userID:conversationData.userID isNeedVideoCall:[TUIChatConfig defaultConfig].enableVideoCall isNeedAudioCall:NO isNeedGroupLive:NO isNeedLink:NO];
        NSMutableArray<TUIInputMoreCellData *> *moreMenus = [TUIChatDataProvider moreMenuCellDataArray:conversationData.groupID userID:conversationData.userID appointId:self.appointment_id];
        moreMenus;
    });
}

//诊室初始化数据
-(void)requestAppointData{
    if((_roomKey && ![_roomKey isEmptyString]) || (_appointment_id && _appointment_id.length>0)){
        if(self.isfirst == YES){
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        }
        self.roomKey = (_roomKey && ![_roomKey isEmptyString])?_roomKey:@"";
        [RequestUtil withPOST:@"/doctor/visit.Visit/roomInfo" parameters:@{@"appointment_id":self.appointment_id,@"doctor_id":self.doctorid,@"roomkey":self.roomKey} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            self.isfirst = NO;
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if(code == 200){
                self.customDic = returnData;
                if(self.customDic.allKeys.count>0){
                    self.patientid = LGNSString(returnData[@"patient"][@"patient_id"]);
                    if(![self.appointment_id containsString:@"999999999-"]){
                        //不是咨询师
                        self.patientNavigation.dataDic = returnData;
                        self.seconds = [returnData[@"count_down"] integerValue];
                        self.inputController.itemView.historyNum = LGNSString(returnData[@"old_count"]);
                        self.inputController.itemView.consultOverBtn.hidden = YES;
                        //10：待支付 20：已取消 30：待接诊 31：咨询中   40 已完成  41：已爽约  42 ：未接通  50：已退款
                        NSString *state = [NSString stringWithFormat:@"%@",returnData[@"state"]];
                        if([state isEqualToString:@"30"]){
                            //待接诊
                            [self.inputController.inputView resignFirstResponder];
                            [self.view addSubview:self.receptView];
                            self.receptView.hidden = NO;
                        }else if ([state isEqualToString:@"31"]){
                            //咨询中
                            self.receptView.hidden = YES;
                            self.inputController.itemView.consultOverBtn.hidden = NO;
                        }else{
                            self.receptView.hidden = YES;
                        }
                        if(self.seconds>0){
                            [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
                            
                        }else{
                            self.patientNavigation.timeLabel.hidden = YES;
                            self.patientNavigation.unitLabel.hidden = YES;
                        }
                    }else{
                        //是咨询师
                        self.teamNavigation.dataDic = returnData;
                    }
                }else{
                    //患者被删除
                    [self.patientNavigation removeFromSuperview];
                    self.patientNavigation = nil;
                    [self.view addSubview:self.teamNavigation];
                    self.teamNavigation.title = self.conversationData.title;
                    [self.view addSubview:self.deleteView];
                    self.timeView.hidden = YES;
                    self.receptView.hidden = YES;
                    self.deleteView.hidden = NO;
                    
                    CGFloat bottomHeight = (TTextView_Height + Bottom_SafeHeight/2.0);
                    self.messageController.view.frame = CGRectMake(0, topBarHeight, viewWidth,viewHeight - topBarHeight-bottomHeight);
                    self.inputController.view.frame = CGRectMake(0, viewHeight - bottomHeight, viewWidth, bottomHeight);
                }
            }
        } error:^(NSError *error) {
            self.isfirst = NO;
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self requestAppointData];
        }];
    }
}

//返回
-(void)backButtonAction{
    if(_timer){
        [self.timer invalidate];
        self.timer = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}


//查看患者详情
-(void)checkPatientDetailAction{
    if(_customDic && _customDic.allKeys.count>0){
        //患者详情
        NSDictionary *tempDic = self.customDic[@"patient"];
        NSString *nodePage = LGNSString(tempDic[@"nodepage"]);
        if ([nodePage isEqualToString:@"1"]) {
            //市一慢阻肺
            LGPatientDetailController2 *controller = [[LGPatientDetailController2 alloc]init];
            controller.patientid = LGNSString(tempDic[@"patient_id"]);
            controller.levelid = LGNSString(tempDic[@"level_id"]);
            controller.diseaseCode = LGNSString(tempDic[@"disease_code"]);
            [self.navigationController pushViewController:controller animated:YES];
        }else{
            //其他
            LGPatientDetailController_YHJK *controller = [[LGPatientDetailController_YHJK alloc]init];
            controller.patientid = LGNSString(tempDic[@"patient_id"]);
            controller.levelid = LGNSString(tempDic[@"level_id"]);
            controller.diseaseCode = LGNSString(tempDic[@"disease_code"]);
            [self.navigationController pushViewController:controller animated:YES];
        }
    }else{
        [TooltipView showMessage:@"此患者已被删除" offset:0];
    }
}

//查看患者详情 -- 之前是查看最新病情概览
-(void)checkDiseaseOverviewAction{
    if(_customDic && _customDic.allKeys.count>0){
        //癌症-患者详情
        NSDictionary *tempDic = self.customDic[@"patient"];
        NSString *nodePage = LGNSString(tempDic[@"nodepage"]);
        if ([nodePage isEqualToString:@"1"]) {
            //市一慢阻肺
            LGPatientDetailController2 *controller = [[LGPatientDetailController2 alloc]init];
            controller.patientid = LGNSString(tempDic[@"patient_id"]);
            controller.levelid = LGNSString(tempDic[@"level_id"]);
            controller.diseaseCode = LGNSString(tempDic[@"disease_code"]);
            [self.navigationController pushViewController:controller animated:YES];
        }else{
            //其他
            LGPatientDetailController_YHJK *controller = [[LGPatientDetailController_YHJK alloc]init];
            controller.patientid = LGNSString(tempDic[@"patient_id"]);
            controller.levelid = LGNSString(tempDic[@"level_id"]);
            controller.diseaseCode = LGNSString(tempDic[@"disease_code"]);
            [self.navigationController pushViewController:controller animated:YES];
        }
        
    }else{
        [TooltipView showMessage:@"此患者已被删除" offset:0];
    }
}

//查看推荐医生详情
-(void)checkDoctorDetail:(NSNotification *)notification{
    NSDictionary *tempDic = notification.userInfo;
    LGPersionalDataController *controller = [[LGPersionalDataController alloc]init];
    controller.userId = LGNSString(tempDic[@"doctorId"]);
    [self.navigationController pushViewController:controller animated:YES];
}

//查看视频咨询订单详情
-(void)checkVideoOrderDetail:(NSNotification *)notification{
    NSDictionary *tempDic = notification.userInfo;
    LGOrderDetailController *controller = [[LGOrderDetailController alloc]init];
    controller.appointId = LGNSString(tempDic[@"appointId"]);
    [self.navigationController pushViewController:controller animated:YES];
}

//服务包详情
-(void)checkServiceDetail:(NSNotification *)notification{
    NSDictionary *tempDic = notification.userInfo;
    LGServiceDetailController *controller = [[LGServiceDetailController alloc]init];
    controller.vipId = LGNSString(tempDic[@"vipId"]);
    [self.navigationController pushViewController:controller animated:YES];
}

//去做量表评估
-(void)checkEvaluationDetail:(NSNotification *)notification{
    NSDictionary *tempDic = notification.userInfo;
    LGGetWebViewController *controller = [[LGGetWebViewController alloc]init];
    controller.urlStr = LGNSString(tempDic[@"urlStr"]);
    [self.navigationController pushViewController:controller animated:YES];
}

//随访及医嘱记录
-(void)checkDoctorAdviceDetail:(NSNotification *)notification{
    NSDictionary *tempDic = notification.userInfo;
    LGFollowAdviceRecordController *controller = [[LGFollowAdviceRecordController alloc]init];
    controller.patientid = self.patientid;
    [self.navigationController pushViewController:controller animated:YES];
}

//查看群成员
-(void)checkTeamMemberAction{
    LGGroupChatMemberController *controller = [[LGGroupChatMemberController alloc]init];
    controller.groupId = LGNSString(self.conversationData.groupID);
    if(_appointment_id && _appointment_id.length>0){
        controller.appointId = self.appointment_id;
    }
    [self.navigationController pushViewController:controller animated:YES];
}

-(void)changeConsultStatusAction{
    self.extendTimeView.hidden = NO;
}

//接诊
-(void)receptConsultAction{
    [RequestUtil withPOST:@"/doctor/visit.Visit/appointmentVisit" parameters:@{@"appointment_id":self.appointment_id} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            [self requestAppointData];
            [UIView animateWithDuration:0.4 animations:^{
                CGRect frame = self.receptView.frame;
                frame.origin.y = viewHeight;
                self.receptView.frame = frame;
            } completion:^(BOOL finished) {
                [self.receptView removeFromSuperview];
                self.receptView = nil;
            }];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        
    }];
}

//拒诊
-(void)refuseConsultAction{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [RequestUtil withPOST:@"/doctor/visit.Visit/appointmentReject" parameters:@{@"appointment_id":self.appointment_id} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if(code == 200){
            [TooltipView showMessage:@"已拒诊" offset:0];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

//延长咨询、结束咨询
-(void)extendTimeViewAction:(UITapGestureRecognizer *)sender{
    self.extendTimeView.hidden = YES;
    [self.view endEditing:YES];
    CGPoint point = [sender locationInView:self.extendTimeView];
    if(point.y<viewPix(82)){
        //延长咨询
        [self.timeView showViewAniamtion];
    }else{
        //结束咨询
        [self appointFinishAction];
    }
}

//结束咨询
-(void)appointFinishAction{
    __weak typeof(self) weakSelf = self;
    [LGAlertTool alertWithTitle:@"结束咨询" content:@"请确认是否已解决了患者的问题，结束咨询后患者将不可再向您发送消息。" sureAction:^{
        if(weakSelf.timer){
            [weakSelf.timer invalidate];
            weakSelf.timer = nil;
        }
        [RequestUtil withPOST:@"/doctor/visit.Visit/appointmentFinish" parameters:@{@"appointment_id":self.appointment_id} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                [self requestAppointData];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            
        }];
    }];
}

//延长咨询时间
-(void)extendTimeAction:(NSString *)hours{
    [RequestUtil withPOST:@"/doctor/visit.Visit/extendExpireTime" parameters:@{@"appointment_id":self.appointment_id,@"hours":hours} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
//            self.seconds = [returnData[@"count_down"] integerValue];
            [self requestAppointData];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        
    }];
}

//倒计时
-(void)countDownAction{
    if(self.seconds>0){
        self.seconds--;
    }else{
        //结束咨询
        [self.timer invalidate];
        self.timer = nil;
        [RequestUtil withPOST:@"/doctor/visit.Visit/appointmentFinish" parameters:@{@"appointment_id":self.appointment_id} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                [self requestAppointData];
            }
        } error:^(NSError *error) {
            
        }];
    }
}

-(void)setSeconds:(NSInteger)seconds{
    _seconds = seconds;
    self.timeView.seconds = seconds;
    NSString *hour = [NSString stringWithFormat:@"%.2ld",seconds/3600];
    NSString *minite = [NSString stringWithFormat:@"%.2ld",(seconds-[hour integerValue]*3600)/60];
    NSString *second = [NSString stringWithFormat:@"%.2ld",seconds%60];
    self.patientNavigation.timeLabel.text = [NSString stringWithFormat:@"%@:%@:%@",hour,minite,second];
}


//视频通话--设置roomid
-(void)createRealCallRoomId:(NSNotification *)notifi{
    NSDictionary *tempDic = notifi.userInfo;
    if(self.canCall == NO) return;
    self.canCall = NO;
    [self performSelector:@selector(canCallAction) withObject:nil afterDelay:2];//防止连续发送
    if(_appointment_id && _appointment_id.length>0 && ![_appointment_id containsString:@"999999999-"]){
        [RequestUtil withPOST:@"/doctor/visit.Visit/setRoomId" parameters:@{@"appointment_id":self.appointment_id,@"room_id":LGNSString(tempDic[@"roomId"])} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            
        } error:^(NSError *error) {
            
        }];
    }
    NSLog(@">>tempDic>>>%@",tempDic);
}

-(void)canCallAction{
    self.canCall = YES;
}

//发送消息
- (void)sendMessage:(V2TIMMessage *)message{
    NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
    if (message.cloudCustomData) {
        //被引用的消息是放在了 cloudCustomData 里
        tempDic = [NSMutableDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:message.cloudCustomData options:NSJSONReadingMutableLeaves error:nil]];
    }
    if (self.needCustomeData == YES) {
        if(_customDic && _customDic.allKeys.count>0){
            //options:0  去掉转JSON时，自动添加的换行符
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self.customDic options:0 error:nil];
            NSString *result = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
            [tempDic setValue:result forKey:@"customMsg"];
            message.cloudCustomData = [NSJSONSerialization dataWithJSONObject:tempDic options:0 error:nil];
            [self.messageController sendMessage:message];
        }else{
            [TooltipView showMessage:@"自定义消息丢失" offset:0];
        }
    }else{
        [tempDic setValue:@{@"needTyping":@(1),@"version":@(1)} forKey:@"messageFeature"];
        message.cloudCustomData = [NSJSONSerialization dataWithJSONObject:tempDic options:0 error:nil];
        [self.messageController sendMessage:message];
    }
}

#pragma mark - Getters & Setters

#pragma mark - Event Response
- (void)onChangeUnReadCount:(UInt64)totalCount {
    /**
     * 此处异步的原因：当前聊天页面连续频繁收到消息，可能还没标记已读，此时也会收到未读数变更。理论上此时未读数不会包括当前会话的。
     * The reason for the asynchrony here: The current chat page receives messages continuously and frequently, it may not be marked as read, and unread changes will also be received at this time. In theory, the unreads at this time will not include the current session.
     */
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.unRead setNum:totalCount];
    });
}







#pragma mark - TUICore notify

- (void)onNotifyEvent:(NSString *)key subKey:(NSString *)subKey object:(id)anObject param:(NSDictionary *)param {
    if ([key isEqualToString:TUICore_TUIConversationNotify]
        && [subKey isEqualToString:TUICore_TUIConversationNotify_SelectConversationSubKey]
        && self.forwardConversationSelectVC == anObject) {
        NSArray<NSDictionary *> *selectList = param[TUICore_TUIConversationNotify_SelectConversationSubKey_ConversationListKey];
        
        NSMutableArray<TUIChatConversationModel *> *targetList = [NSMutableArray arrayWithCapacity:selectList.count];
        for (NSDictionary *selectItem in selectList) {
            TUIChatConversationModel *model = [TUIChatConversationModel new];
            model.title = selectItem[TUICore_TUIConversationNotify_SelectConversationSubKey_ItemTitleKey];
            model.userID = selectItem[TUICore_TUIConversationNotify_SelectConversationSubKey_ItemUserIDKey];
            model.groupID = selectItem[TUICore_TUIConversationNotify_SelectConversationSubKey_ItemGroupIDKey];
            model.conversationID = selectItem[TUICore_TUIConversationNotify_SelectConversationSubKey_ItemConversationIDKey];
            [targetList addObject:model];
        }
        
        [self forwardMessages:self.forwardSelectUIMsgs toTargets:targetList merge:self.isMergeForward];
        self.forwardSelectUIMsgs = nil;
        
        if (self.translatedText.length > 0) {
            [self forwardTranslationText:self.translatedText toConverations:targetList];
            self.translatedText = nil;
        }
    }else if ([key isEqualToString:TUICore_TUIConversationNotify] && [subKey isEqualToString:TUICore_TUIConversationNotify_ClearConversationUIHistorySubKey]) {
        [self.messageController clearUImsg];
    }
}


#pragma mark - TUIInputControllerDelegate
- (void)inputController:(TUIInputController *)inputController didChangeHeight:(CGFloat)height {
    if (!self.responseKeyboard) {
        return;
    }
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        CGRect msgFrame = self.messageController.view.frame;
        msgFrame.size.height = viewHeight - height - topMargin;
        self.messageController.view.frame = msgFrame;

        CGRect inputFrame = self.inputController.view.frame;
        inputFrame.origin.y = msgFrame.origin.y + msgFrame.size.height;
        inputFrame.size.height = height;
        self.inputController.view.frame = inputFrame;
        [self.messageController scrollToBottom:NO];
    } completion:nil];
}

- (void)inputController:(TUIInputController *)inputController didSendMessage:(V2TIMMessage *)msg {
    [self sendMessage:msg];
}

//点击扩展按钮
- (void)inputController:(TUIInputController *)inputController didSelectMoreCell:(TUIInputMoreCell *)cell {
    cell.disableDefaultSelectAction = NO;
    
    if (cell.disableDefaultSelectAction) {
        return;
    }
    
    if ([cell.data.key isEqualToString:[TUIInputMoreCellData photoData].key]) {
        //照片
        [self.mediaProvider selectPhoto];
        
    } else if ([cell.data.key isEqualToString:[TUIInputMoreCellData pictureData].key]) {
        //拍照
        [self.mediaProvider takePicture];
        
    } else if ([cell.data.key isEqualToString:[TUIInputMoreCellData videoData].key]) {
        //拍摄视频
        [self.mediaProvider takeVideo];
        
    } else if ([cell.data.key isEqualToString:[TUIInputMoreCellData fileData].key]) {
        //文件
        [self.mediaProvider selectFile];
        
    }else if ([cell.data.key isEqualToString:[TUIInputMoreCellData chronicDisease].key]){
        //慢病服务
        LGRecommendServiceController *controller = [[LGRecommendServiceController alloc]init];
        controller.timID = (self.conversationData.userID&&self.conversationData.userID.length>0)?self.conversationData.userID:self.conversationData.groupID;
        controller.appointment_id = self.appointment_id;
        [self.navigationController pushViewController:controller animated:YES];
        
    }else if ([cell.data.key isEqualToString:[TUIInputMoreCellData recommendDoctor].key]){
        //推荐医生
        LGRecommendDoctorController *controller = [[LGRecommendDoctorController alloc]init];
        controller.timID = (self.conversationData.userID&&self.conversationData.userID.length>0)?self.conversationData.userID:self.conversationData.groupID;
        controller.appointment_id = self.appointment_id;
        [self.navigationController pushViewController:controller animated:YES];
        
    }else if ([cell.data.key isEqualToString:[TUIInputMoreCellData sendEvaluation].key]){
        //发送评估
        if (_customDic && [_customDic isKindOfClass:[NSDictionary class]] && _customDic.allKeys.count>0) {
            NSDictionary *tempDic = self.customDic[@"patient"];
            LGSendEvaluationController *controller = [[LGSendEvaluationController alloc]init];
                controller.patientid = LGNSString(tempDic[@"patient_id"]);
                controller.levelid = LGNSString(tempDic[@"level_id"]);
            controller.timID = (self.conversationData.userID&&self.conversationData.userID.length>0)?self.conversationData.userID:self.conversationData.groupID;
            controller.appointment_id = self.appointment_id;
            [self.navigationController pushViewController:controller animated:YES];
        }else{
            [TooltipView showMessage:@"缺少用户信息" offset:0];
        }
        
    }else if ([cell.data.key isEqualToString:[TUIInputMoreCellData huaYiTongConsult].key]){
        //华医通咨询
        
    }else if ([cell.data.key isEqualToString:[TUIInputMoreCellData visitAppointment].key]){
        //复诊预约
        
    }else if ([cell.data.key isEqualToString:TUIInputMoreCellKey_Poll]) {
        NSDictionary *param = @{TUICore_TUIPollService_GetCreatePollVCMethod_GroupIDKey: self.conversationData.groupID};
        UIViewController *vc = (UIViewController *)[TUICore callService:TUICore_TUIPollService
                                                                 method:TUICore_TUIPollService_GetCreatePollVCMethod
                                                                  param:param];
        [self.navigationController pushViewController:vc animated:YES];
        [self.inputController reset];
        self.needScrollToBottom = YES;
    } else if ([cell.data.key isEqualToString:TUIInputMoreCellKey_GroupNote]) {
        NSDictionary *param = @{TUICore_TUIGroupNoteService_GetGroupNoteCreateVCMethod_GroupIDKey: self.conversationData.groupID};
        UIViewController *vc = (UIViewController *)[TUICore callService:TUICore_TUIGroupNoteService
                                                                 method:TUICore_TUIGroupNoteService_GetGroupNoteCreateVCMethod
                                                                  param:param];
        [self.navigationController pushViewController:vc animated:YES];
        [self.inputController reset];
        self.needScrollToBottom = YES;
    }
}

- (void)inputControllerDidInputAt:(TUIInputController *)inputController {
    /**
     * 交给 GroupChatVC 去处理
     * Handle to GroupChatVC
     */
}

- (void)inputController:(TUIInputController *)inputController didDeleteAt:(NSString *)atText {
    /**
     * 交给 GroupChatVC 去处理
     * Handle to GroupChatVC
     */
}

-(void)inputController:(TUIInputController *)inputController didSelectCustomItem:(NSString *)type{
    if([type isEqualToString:@"history"]){
        //历史聊天记录
        LGConsultHistoryController *controller = [[LGConsultHistoryController alloc]init];
        controller.appointid = self.appointment_id;
        controller.dataDic = self.customDic;
        [self.navigationController pushViewController:controller animated:YES];
        
    }else if([type isEqualToString:@"consultSummary"]){
        //发送医嘱
        LGAddDoctorAdviceController *controller = [[LGAddDoctorAdviceController alloc]init];
        controller.patientid = LGNSString(self.customDic[@"patient"][@"patient_id"]);
        controller.followid = @"0";
        controller.appointid = self.appointment_id;
        controller.source = @"chat";
        [self.navigationController pushViewController:controller animated:YES];
        
    }else{
        //结束咨询
        [self appointFinishAction];
    }
}

- (void)inputControllerBeginTyping:(TUIInputController *)inputController {
    
    //for C2CChatVC
}

- (void)inputControllerEndTyping:(TUIInputController *)inputController {
    //for C2CChatVC
}

#pragma mark - TUIBaseMessageControllerDelegate
- (void)didTapInMessageController:(TUIBaseMessageController *)controller {
    [self.inputController reset];
}

- (BOOL)messageController:(TUIBaseMessageController *)controller willShowMenuInCell:(TUIMessageCell *)cell {
    if([self.inputController.inputBar.inputTextView isFirstResponder]){
        self.inputController.inputBar.inputTextView.overrideNextResponder = cell;
        return YES;
    }
    return NO;
}

- (TUIMessageCellData *)messageController:(TUIBaseMessageController *)controller onNewMessage:(V2TIMMessage *)message {
    return nil;
}

- (TUIMessageCell *)messageController:(TUIBaseMessageController *)controller onShowMessageData:(TUIMessageCellData *)data {
    return nil;
}

- (void)messageController:(TUIBaseMessageController *)controller willDisplayCell:(TUIMessageCell *)cell withData:(TUIMessageCellData *)cellData {
    if([cell isKindOfClass:[TUIJoinGroupMessageCell class]]){
        TUIJoinGroupMessageCell *joinCell = (TUIJoinGroupMessageCell *)cell;
        joinCell.joinGroupDelegate = self;
    }
}

//点击用户头像
- (void)messageController:(TUIBaseMessageController *)controller onSelectMessageAvatar:(TUIMessageCell *)cell {
    if (cell.messageData.identifier == nil) {
        [TooltipView showMessage:@"用户未知" offset:0];
        return;
    }
    V2TIMMessage *message = cell.messageData.innerMessage;
    if ([message.sender containsString:@"doctor"]) {
        //跳转到医生
        LGPersionalDataController *controller = [[LGPersionalDataController alloc]init];
        controller.userId = message.sender;
        [self.navigationController pushViewController:controller animated:YES];
        return;
    }
   
    NSDictionary *tempDic = self.customDic[@"patient"];
    if ([tempDic isKindOfClass:[NSDictionary class]] && tempDic.allKeys.count>0) {
        //跳转到患者详情
        NSString *nodePage = LGNSString(tempDic[@"nodepage"]);
        if ([nodePage isEqualToString:@"1"]) {
            //市一慢阻肺
            LGPatientDetailController2 *controller = [[LGPatientDetailController2 alloc]init];
            controller.patientid = LGNSString(tempDic[@"patient_id"]);
            controller.levelid = LGNSString(tempDic[@"level_id"]);
            controller.diseaseCode = LGNSString(tempDic[@"disease_code"]);
            [self.navigationController pushViewController:controller animated:YES];
        }else{
            //其他
            LGPatientDetailController_YHJK *controller = [[LGPatientDetailController_YHJK alloc]init];
            controller.patientid = LGNSString(tempDic[@"patient_id"]);
            controller.levelid = LGNSString(tempDic[@"level_id"]);
            controller.diseaseCode = LGNSString(tempDic[@"disease_code"]);
            [self.navigationController pushViewController:controller animated:YES];
        }
    }
    
    NSDictionary *customeDic = nil;
    if(message.cloudCustomData){
        customeDic = [NSJSONSerialization JSONObjectWithData:message.cloudCustomData options:NSJSONReadingMutableLeaves error:nil];
    }
    if(customeDic && [customeDic isKindOfClass:[NSDictionary class]] && [customeDic.allKeys count]>0 && [customeDic.allKeys containsObject:@"customMsg"]){
        NSLog(@">>>???>>>%@",[ObjectTool jsonToObject:customeDic[@"customMsg"]]);
    }
}

//选中消息
- (void)messageController:(TUIBaseMessageController *)controller onSelectMessageContent:(TUIMessageCell *)cell {
    self.extendTimeView.hidden = YES;
    cell.disableDefaultSelectAction = NO;
    if (cell.disableDefaultSelectAction) {
        return;
    }
}

//点击菜单选项
- (void)messageController:(TUIBaseMessageController *)controller onSelectMessageMenu:(NSInteger)menuType withData:(TUIMessageCellData *)data {
    [self onSelectMessageMenu:menuType withData:data];
}

- (void)didHideMenuInMessageController:(TUIBaseMessageController *)controller {
    self.inputController.inputBar.inputTextView.overrideNextResponder = nil;
}

- (void)messageController:(TUIBaseMessageController *)controller onReEditMessage:(TUIMessageCellData *)data {
    V2TIMMessage *message = data.innerMessage;
    if (message.elemType == V2TIM_ELEM_TYPE_TEXT) {
        NSString *text = message.textElem.text;
        self.inputController.inputBar.inputTextView.text = text;
        [self.inputController.inputBar.inputTextView becomeFirstResponder];
    }
}



#pragma mark - TUIChatBaseDataProviderForwardDelegate
- (NSString *)dataProvider:(TUIChatDataProvider *)dataProvider mergeForwardTitleWithMyName:(NSString *)name{
    return @"";
}

- (NSString *)dataProvider:(TUIChatDataProvider *)dataProvider mergeForwardMsgAbstactForMessage:(V2TIMMessage *)message {
    return @"";
}



#pragma mark - 消息菜单操作: 多选 & 转发
- (void)onSelectMessageMenu:(NSInteger)menuType withData:(TUIMessageCellData *)data {
    if (menuType == 0) {
        [self openMultiChooseBoard:YES];
    } else if (menuType == 1) {
        if (data == nil) {
            return;
        }
        NSMutableArray *uiMsgs = [NSMutableArray arrayWithArray:@[data]];
        [self prepareForwardMessages:uiMsgs];
    }
}

- (void)openMultiChooseBoard:(BOOL)open {
    [self.view endEditing:YES];
    
    if (_multiChooseView) {
        [_multiChooseView removeFromSuperview];
    }
    
    if (open) {
        _multiChooseView = [[TUIMessageMultiChooseView alloc] init];
        _multiChooseView.frame = UIScreen.mainScreen.bounds;
        _multiChooseView.delegate = self;
        _multiChooseView.titleLabel.text = self.conversationData.title;
        if (@available(iOS 12.0, *)) {
            if (@available(iOS 13.0, *)) {
                // > ios 12
                [UIApplication.sharedApplication.keyWindow addSubview:_multiChooseView];
            } else {
                // ios = 12
                UIView *view = self.navigationController.view;
                if (view == nil) {
                    view = self.view;
                }
                [view addSubview:_multiChooseView];
            }
        } else {
            // < ios 12
            [UIApplication.sharedApplication.keyWindow addSubview:_multiChooseView];
        }
    } else {
        [self.messageController enableMultiSelectedMode:NO];
    }
}

- (void)messageMultiChooseViewOnCancelClicked:(TUIMessageMultiChooseView *)multiChooseView {
    [self openMultiChooseBoard:NO];
    [self.messageController enableMultiSelectedMode:NO];
}

- (void)messageMultiChooseViewOnRelayClicked:(TUIMessageMultiChooseView *)multiChooseView {
    NSArray *uiMsgs = [self.messageController multiSelectedResult:TUIMultiResultOptionAll];
    [self prepareForwardMessages:uiMsgs];
}

- (void)messageMultiChooseViewOnDeleteClicked:(TUIMessageMultiChooseView *)multiChooseView {
    NSArray *uiMsgs = [self.messageController multiSelectedResult:TUIMultiResultOptionAll];
    if (uiMsgs.count == 0) {
        [TUITool makeToast:TUIKitLocalizableString(TUIKitRelayNoMessageTips)];
        return;
    }
    
    [self.messageController deleteMessages:uiMsgs];
    [self openMultiChooseBoard:NO];
    [self.messageController enableMultiSelectedMode:NO];
}

- (void)prepareForwardMessages:(NSArray<TUIMessageCellData *> *)uiMsgs {
    if (uiMsgs.count == 0) {
        [TUITool makeToast:TUIKitLocalizableString(TUIKitRelayNoMessageTips)];
        return;
    }

    BOOL hasSendFailedMsg = NO;
    BOOL hasPluginMsg = NO;
    for (TUIMessageCellData *data in uiMsgs) {
        if (data.status != Msg_Status_Succ) {
            hasSendFailedMsg = YES;
        }
        if ([data isKindOfClass:TUIPollContainerCellData.class] ||
            [data isKindOfClass:TUIGroupNoteContainerCellData.class]) {
            hasPluginMsg = YES;
        }
        if (hasSendFailedMsg && hasPluginMsg) {
            break;
        }
    }
    
    if (hasSendFailedMsg) {
        UIAlertController *vc = [UIAlertController alertControllerWithTitle:TUIKitLocalizableString(TUIKitRelayUnsupportForward) message:nil preferredStyle:UIAlertControllerStyleAlert];
        [vc tuitheme_addAction:[UIAlertAction actionWithTitle:TUIKitLocalizableString(Confirm) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:vc animated:YES completion:nil];
        return;
    }
    
    if (hasPluginMsg) {
        UIAlertController *vc = [UIAlertController alertControllerWithTitle:TUIKitLocalizableString(TUIKitRelayPluginNotAllowed) message:nil preferredStyle:UIAlertControllerStyleAlert];
        [vc tuitheme_addAction:[UIAlertAction actionWithTitle:TUIKitLocalizableString(Confirm) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:vc animated:YES completion:nil];
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    void(^chooseTarget)(BOOL) = ^(BOOL mergeForward) {
        UIViewController * vc = (UIViewController *)[TUICore callService:TUICore_TUIConversationService method:TUICore_TUIConversationService_GetConversationSelectControllerMethod param:nil];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:(UIViewController *)vc];
        nav.modalPresentationStyle = UIModalPresentationFullScreen;
        weakSelf.forwardConversationSelectVC = (UIViewController *)vc;
        weakSelf.forwardSelectUIMsgs = uiMsgs;
        weakSelf.isMergeForward = mergeForward;
        [weakSelf presentViewController:nav animated:YES completion:nil];
    };
    
    UIAlertController *tipsVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    /**
     * 逐条转发
     * Forward one-by-one
     */
    [tipsVc tuitheme_addAction:[UIAlertAction actionWithTitle:TUIKitLocalizableString(TUIKitRelayOneByOneForward) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (uiMsgs.count <= 30) {
            chooseTarget(NO);
            return;
        }
        UIAlertController *vc = [UIAlertController alertControllerWithTitle:TUIKitLocalizableString(TUIKitRelayOneByOnyOverLimit) message:nil preferredStyle:UIAlertControllerStyleAlert];
        [vc tuitheme_addAction:[UIAlertAction actionWithTitle:TUIKitLocalizableString(Cancel) style:UIAlertActionStyleDefault handler:nil]];
        [vc tuitheme_addAction:[UIAlertAction actionWithTitle:TUIKitLocalizableString(TUIKitRelayCombineForwad) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            chooseTarget(YES);
        }]];
        [weakSelf presentViewController:vc animated:YES completion:nil];
    }]];
    
    /**
     * 合并转发
     * Merge-forward
     */
    [tipsVc tuitheme_addAction:[UIAlertAction actionWithTitle:TUIKitLocalizableString(TUIKitRelayCombineForwad) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        chooseTarget(YES);
    }]];
    [tipsVc tuitheme_addAction:[UIAlertAction actionWithTitle:TUIKitLocalizableString(Cancel) style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:tipsVc animated:YES completion:nil];
}

- (void)forwardMessages:(NSArray<TUIMessageCellData *> *)uiMsgs
              toTargets:(NSArray<TUIChatConversationModel *> *)targets
                  merge:(BOOL)merge {
    if (uiMsgs.count == 0 || targets.count == 0) {
        return ;
    }

    @weakify(self);
    [self.dataProvider getForwardMessageWithCellDatas:uiMsgs
                                            toTargets:targets
                                                Merge:merge
                                          ResultBlock:^(TUIChatConversationModel * _Nonnull targetConversation, NSArray<V2TIMMessage *> * _Nonnull msgs) {
        @strongify(self);

        TUIChatConversationModel *convCellData = targetConversation;
        NSTimeInterval timeInterval = convCellData.groupID.length?0.09:0.05;

        /**
         * 发送到当前聊天窗口
         * Forward to currernt chat vc
         */
        if ([convCellData.conversationID isEqualToString:self.conversationData.conversationID]) {
            for (V2TIMMessage *imMsg in msgs) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    /**
                     * 下面的函数涉及到 UI 的刷新，要放在主线程操作
                     * The following functions involve the refresh of the UI and should be called on the main thread
                     */
                    [self.messageController sendMessage:imMsg];
                });

                /**
                 * 此处的延时操作是为了在批量逐条转发时，尽可能保证接收端的顺序
                 * The delay here is to ensure the order of the receiving end as much as possible when forwarding in batches one by one
                 */
                [NSThread sleepForTimeInterval:timeInterval];
            }
            return;
        }

        /**
         * 发送到其他聊天
         * Forward to other chat user
         */
        for (V2TIMMessage *message in msgs) {
            message.needReadReceipt = [TUIChatConfig defaultConfig].msgNeedReadReceipt;
            [TUIMessageDataProvider sendMessage:message
                                 toConversation:convCellData
                                 isSendPushInfo:YES
                               isOnlineUserOnly:NO
                                       priority:V2TIM_PRIORITY_NORMAL
                                       Progress:nil
                                      SuccBlock:^{
                /**
                 * 发送到其他聊天的消息需要广播消息发送状态，方便进入对应聊天后刷新消息状态
                 * Messages sent to other chats need to broadcast the message sending status, which is convenient to refresh the message status after entering the corresponding chat
                 */
                [NSNotificationCenter.defaultCenter postNotificationName:TUIKitNotification_onMessageStatusChanged object:message.msgID];
            } FailBlock:^(int code, NSString *desc) {
                [NSNotificationCenter.defaultCenter postNotificationName:TUIKitNotification_onMessageStatusChanged object:message.msgID];
            }];

            /**
             * 此处的延时操作是为了在批量逐条转发时，尽可能保证接收端的顺序
             * The delay here is to ensure the order of the receiving end as much as possible when forwarding in batches one by one
             */
            [NSThread sleepForTimeInterval:timeInterval];
        }
    } fail:^(int code, NSString *desc) {
        NSLog(@"%@", desc);
        NSAssert(NO, desc);
    }];
}



#pragma mark - Message reply
- (void)messageController:(TUIBaseMessageController *)controller onRelyMessage:(nonnull TUIMessageCellData *)data {
    @weakify(self)
    [self.inputController exitReplyAndReference:^{
        @strongify(self)
        NSString *desc = @"";
        desc = [self replyReferenceMessageDesc:data];
        
        TUIReplyPreviewData *replyData = [[TUIReplyPreviewData alloc] init];
        replyData.msgID = data.msgID;
        replyData.msgAbstract = desc;
        replyData.sender = data.name;
        replyData.type = (NSInteger)data.innerMessage.elemType;
        replyData.originMessage = data.innerMessage;
        
        NSMutableDictionary *cloudResultDic = [[NSMutableDictionary alloc] initWithCapacity:5];
        if (replyData.originMessage.cloudCustomData) {
            NSDictionary * originDic = [TUITool jsonData2Dictionary:replyData.originMessage.cloudCustomData];
            if (originDic && [originDic isKindOfClass:[NSDictionary class]]) {
                [cloudResultDic addEntriesFromDictionary:originDic];
            }
        }
        NSString * messageParentReply = cloudResultDic[@"messageReply"];
        NSString * messageRootID = [messageParentReply valueForKey:@"messageRootID"];
        if (!IS_NOT_EMPTY_NSSTRING(messageRootID)) {
            /**
             * 源消息没有 messageRootID， 则需要将当前源消息的 msgID 作为 root
             * If the original message does not have messageRootID, you need to make the msgID of the current original message as the root
             */
            if (IS_NOT_EMPTY_NSSTRING(replyData.originMessage.msgID)) {
                messageRootID = replyData.originMessage.msgID;
            }
        }
        
        replyData.messageRootID =  messageRootID;
        [self.inputController showReplyPreview:replyData];
    }];
    
}
- (NSString *)replyReferenceMessageDesc:(TUIMessageCellData *)data {
    NSString *desc = @"";
    if (data.innerMessage.elemType == V2TIM_ELEM_TYPE_FILE) {
        desc = data.innerMessage.fileElem.filename;
    } else if (data.innerMessage.elemType == V2TIM_ELEM_TYPE_MERGER) {
        desc = data.innerMessage.mergerElem.title;
    } else if (data.innerMessage.elemType == V2TIM_ELEM_TYPE_CUSTOM) {
        desc = [TUIMessageDataProvider getDisplayString:data.innerMessage];
    } else if (data.innerMessage.elemType == V2TIM_ELEM_TYPE_TEXT) {
        desc = data.innerMessage.textElem.text;
    }
    return desc;
}
#pragma mark - Message quote
- (void)messageController:(TUIBaseMessageController *)controller onReferenceMessage:(TUIMessageCellData *)data {
    @weakify(self)
    [self.inputController exitReplyAndReference:^{
        @strongify(self)
        NSString *desc = @"";
        desc = [self replyReferenceMessageDesc:data];
        
        TUIReferencePreviewData *referenceData = [[TUIReferencePreviewData alloc] init];
        referenceData.msgID = data.msgID;
        referenceData.msgAbstract = desc;
        referenceData.sender = data.name;
        referenceData.type = (NSInteger)data.innerMessage.elemType;
        referenceData.originMessage = data.innerMessage;
        [self.inputController showReferencePreview:referenceData];
    }];
}

#pragma mark - Message react
/*
 "messageReact": {
     "reacts": [
         {
             "emojiId1": ["userId1","userId2"]
         },
         {
             "emojiId2": ["userId3","userId4"]
         },
     ],
     "version": "1",
 }
 */
- (void)messageController:(TUIBaseMessageController *)controller modifyMessage:(nonnull TUIMessageCellData *)cellData reactEmoji:(NSString *)emojiName{
    
    V2TIMMessage *rootMsg = cellData.innerMessage;

    [[TUIChatModifyMessageHelper defaultHelper] modifyMessage:rootMsg reactEmoji:emojiName];
}

#pragma mark - Message translation forward
- (void)messageController:(TUIBaseMessageController *)controller
     onForwardTranslation:(NSString *)text {
    if (text.length == 0) {
        return;
    }
    self.translatedText = text;
    [self presentConverationSelectVC];
}

- (void)presentConverationSelectVC {
    UIViewController *vc = (UIViewController *)[TUICore callService:TUICore_TUIConversationService method:TUICore_TUIConversationService_GetConversationSelectControllerMethod param:nil];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:(UIViewController *)vc];
    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    self.forwardConversationSelectVC = (UIViewController *)vc;
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)forwardTranslationText:(NSString *)text
                toConverations:(NSArray <TUIChatConversationModel *> *)conversations {
    for (TUIChatConversationModel *conversation in conversations) {
        V2TIMMessage *message = [[V2TIMManager sharedInstance] createTextMessage:text];
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([conversation.conversationID isEqualToString:self.conversationData.conversationID]) {
                // Send translated text to myself
                [self.messageController sendMessage:message];
            } else {
                // Send to other conversation
                message.needReadReceipt = [TUIChatConfig defaultConfig].msgNeedReadReceipt;
                [TUIMessageDataProvider sendMessage:message
                                     toConversation:conversation
                                     isSendPushInfo:YES
                                   isOnlineUserOnly:NO
                                           priority:V2TIM_PRIORITY_NORMAL
                                           Progress:nil
                                          SuccBlock:^{
                    [NSNotificationCenter.defaultCenter postNotificationName:TUIKitNotification_onMessageStatusChanged
                                                                      object:message.msgID];
                } FailBlock:^(int code, NSString *desc) {
                    [NSNotificationCenter.defaultCenter postNotificationName:TUIKitNotification_onMessageStatusChanged
                                                                      object:message.msgID];
                }];
            }
        });
    }
}

#pragma mark - Private Methods


#pragma mark - TUIJoinGroupMessageCellDelegate
- (void)didTapOnRestNameLabel:(TUIJoinGroupMessageCell *)cell withIndex:(NSInteger)index{
    NSString *userId = cell.joinData.userIDList[index];
    
//    [self getUserOrFriendProfileVCWithUserID:userId succBlock:^(UIViewController *vc) {
//        [self.navigationController pushViewController:vc animated:YES];
//    } failBlock:^(int code, NSString *desc) {
//        [TUITool makeToastError:code msg:desc];
//    }];
}

#pragma mark - V2TIMConversationListener
//onConversationChanged
- (void)onNewConversation:(NSArray<V2TIMConversation*> *) conversationList {
    for (V2TIMConversation *conv in conversationList) {
//        if ([conv.conversationID isEqualToString:self.conversationData.conversationID]) {
        if ((conv.type == V2TIM_C2C && [conv.userID isEqualToString:self.conversationData.userID]) || (conv.type == V2TIM_GROUP && [conv.groupID isEqualToString:self.conversationData.groupID])) {
            V2TIMMessage *msg = conv.lastMessage;
            if (msg.customElem != nil && msg.customElem.data != nil) {
                NSDictionary *param = [TUITool jsonData2Dictionary:msg.customElem.data];
                if (param != nil && [param isKindOfClass:[NSDictionary class]]) {
                    NSString *businessID = LGNSString(param[@"businessID"]);
                    NSLog(@">>>收到自定义消息>>>%@",businessID);
                    if([businessID isEqualToString:@"TIMCustom_01"] || [businessID isEqualToString:@"TIMCustom_02"] || [businessID isEqualToString:@"TIMCustom_03"]|| [businessID isEqualToString:@"TIMCustom_05"]|| [businessID isEqualToString:@"TIMCustom_07"]|| [businessID isEqualToString:@"TIMCustom_11"]|| [businessID isEqualToString:@"TIMCustom_13"]|| [businessID isEqualToString:@"TIMCustom_18"]|| [businessID isEqualToString:@"TIMCustom_20"]|| [businessID isEqualToString:@"TIMCustom_30"]|| [businessID isEqualToString:@"TIMCustom_31"]){
                        //需要刷新的消息
                        if(msg.cloudCustomData){
                            NSDictionary *customDic = [NSJSONSerialization JSONObjectWithData:msg.cloudCustomData options:NSJSONReadingMutableLeaves error:nil];
                            if([customDic.allKeys containsObject:@"customMsg"]){
                                customDic = [ObjectTool jsonToObject:customDic[@"customMsg"]];
                                self.appointment_id = LGNSString(customDic[@"appointment_id"]);
                                if(_timer){
                                    [self.timer invalidate];
                                    self.timer = nil;
                                }
                                [self requestAppointData];
                            }
                        }
                    }
                }
            }
            if (!self.conversationData.otherSideTyping) {
                self.conversationData.title = conv.showName;
            }
            break;
        }
    }
}

#pragma mark - FriendInfoChangedNotification


#pragma mark - Media Provider
- (void)onProvideImage:(NSString *)imageUrl {
    V2TIMMessage *message = [V2TIMManager.sharedInstance createImageMessage:imageUrl];
    [self sendMessage:message];
}

- (void)onProvideImageError:(NSString *)errorMessage {
    [TUITool makeToast:errorMessage];
}

- (void)onProvideVideo:(NSString *)videoUrl snapshot:(NSString *)snapshotUrl duration:(NSInteger)duration {
    V2TIMMessage *message = [V2TIMManager.sharedInstance createVideoMessage:videoUrl type:videoUrl.pathExtension duration:(int)duration snapshotPath:snapshotUrl];
    [self sendMessage:message];
}

- (void)onProvideVideoError:(NSString *)errorMessage {
    [TUITool makeToast:errorMessage];
}

- (void)onProvideFile:(NSString *)fileUrl filename:(NSString *)filename fileSize:(NSInteger)fileSize {
    V2TIMMessage *message = [V2TIMManager.sharedInstance createFileMessage:fileUrl fileName:filename];
    [self sendMessage:message];
}

- (void)onProvideFileError:(NSString *)errorMessage {
    [TUITool makeToast:errorMessage];
}

#pragma mark ====>
//好友信息变化
- (void)onFriendInfoChanged:(NSNotification *)notice{
    if (self.conversationData.userID.length > 0) {
        self.conversationData.title = self.conversationData.userID;
        @weakify(self);
        
        [TUIChatDataProvider getFriendInfoWithUserId:self.conversationData.userID SuccBlock:^(V2TIMFriendInfoResult * _Nonnull friendInfoResult) {
            @strongify(self);
            if (friendInfoResult.relation & V2TIM_FRIEND_RELATION_TYPE_IN_MY_FRIEND_LIST
                && friendInfoResult.friendInfo.friendRemark.length > 0) {
                self.conversationData.title = friendInfoResult.friendInfo.friendRemark;
            } else {
                [TUIChatDataProvider getUserInfoWithUserId:friendInfoResult.friendInfo.userID
                                               SuccBlock:^(V2TIMUserFullInfo * _Nonnull userInfo) {
                    if (userInfo.nickName.length > 0) {
                        self.conversationData.title = userInfo.nickName;
                    }
                } failBlock:nil];
            }
        } failBlock:nil];
    }else if (self.conversationData.groupID.length > 0) {
        [TUIChatDataProvider getGroupInfoWithGroupID:self.conversationData.groupID SuccBlock:^(V2TIMGroupInfoResult * _Nonnull groupResult) {
            if (groupResult.info.groupName.length > 0) {
                self.conversationData.title = groupResult.info.groupName;
            }
        } failBlock:nil];
    }
}

//保存草稿内容
- (void)saveDraftContent{
    NSString *content = [self.inputController.inputBar.inputTextView.textStorage getPlainString];
    
    TUIReplyPreviewData * previewData = nil;
    if (self.inputController.referenceData) {
        previewData  = self.inputController.referenceData;
    }else if(self.inputController.replyData) {
        previewData  = self.inputController.replyData;
    }
    if (previewData) {
        
        NSDictionary *dict = @{
            @"content" : content?:@"",
            @"messageReply" : @{
                    @"messageID"       : previewData.msgID?:@"",
                    @"messageAbstract" : [previewData.msgAbstract?:@"" getInternationalStringWithfaceContent],
                    @"messageSender"   : previewData.sender?:@"",
                    @"messageType"     : @(previewData.type),
                    @"messageTime"     : @(previewData.originMessage.timestamp ? [previewData.originMessage.timestamp timeIntervalSince1970] : 0),  // Compatible for web
                    @"messageSequence" : @(previewData.originMessage.seq),// Compatible for web
                    @"version"         : @(kDraftMessageReplyVersion),
            },
        };
        NSMutableDictionary *mudic = [NSMutableDictionary dictionaryWithDictionary:dict];
        
        if (IS_NOT_EMPTY_NSSTRING(previewData.messageRootID)) {
            [mudic setObject:previewData.messageRootID forKey:@"messageRootID"];
        }
        NSError *error = nil;
        NSData *data = [NSJSONSerialization dataWithJSONObject:mudic options:0 error:&error];
        if (error == nil) {
            content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        }
    }
    [TUIChatDataProvider saveDraftWithConversationID:self.conversationData.conversationID Text:content];

}

//加载草稿内容
- (void)loadDraftContent{
    NSString *draft = self.conversationData.draftText;
    if (draft.length == 0) {
        return;
    }
    
    NSError *error = nil;
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[draft dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
    if (error || jsonDict == nil) {
                
        NSMutableAttributedString *formatEmojiString = [draft getAdvancedFormatEmojiStringWithFont:kTUIInputNoramlFont textColor:kTUIInputNormalTextColor emojiLocations:nil];

        
        [self.inputController.inputBar.inputTextView.textStorage insertAttributedString:formatEmojiString atIndex:0];
        return;
    }
    
    /**
     * 显示草稿
     * Display draft
     */
    NSString *draftContent = [jsonDict.allKeys containsObject:@"content"] ? jsonDict[@"content"] : @"";
    
    NSMutableAttributedString *formatEmojiString = [draftContent getAdvancedFormatEmojiStringWithFont:kTUIInputNoramlFont textColor:kTUIInputNormalTextColor emojiLocations:nil];

    [self.inputController.inputBar.inputTextView.textStorage insertAttributedString:formatEmojiString atIndex:0];
    
    NSString *messageRootID = [jsonDict.allKeys containsObject:@"messageRootID"] ? jsonDict[@"messageRootID"] : @"";

    /**
     * 显示消息回复预览
     * Display message reply preview bar
     */
    if ([jsonDict isKindOfClass:NSDictionary.class] && [jsonDict.allKeys containsObject:@"messageReply"]) {
        NSDictionary *reply = jsonDict[@"messageReply"];
        if ([reply isKindOfClass:NSDictionary.class] &&
            [reply.allKeys containsObject:@"messageID"] &&
            [reply.allKeys containsObject:@"messageAbstract"] &&
            [reply.allKeys containsObject:@"messageSender"] &&
            [reply.allKeys containsObject:@"messageType"] &&
            [reply.allKeys containsObject:@"version"]) {
            NSInteger version = [reply[@"version"] integerValue];
            if (version <= kDraftMessageReplyVersion) {

                if (IS_NOT_EMPTY_NSSTRING(messageRootID)) {
                    TUIReplyPreviewData *replyData = [[TUIReplyPreviewData alloc] init];
                    replyData.msgID       = reply[@"messageID"];
                    replyData.msgAbstract = reply[@"messageAbstract"];
                    replyData.sender      = reply[@"messageSender"];
                    replyData.type        = [reply[@"messageType"] integerValue];
                    replyData.messageRootID = messageRootID;
                    [self.inputController showReplyPreview:replyData];
                }
                else {
                    TUIReferencePreviewData *replyData = [[TUIReferencePreviewData alloc] init];
                    replyData.msgID       = reply[@"messageID"];
                    replyData.msgAbstract = reply[@"messageAbstract"];
                    replyData.sender      = reply[@"messageSender"];
                    replyData.type        = [reply[@"messageType"] integerValue];
                    [self.inputController showReferencePreview:replyData];
                }
            }
        }
    }
}




- (void)dealloc {
    [TUICore unRegisterEventByObject:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark
#pragma mark ====> 创建控件

+ (void)createCachePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:TUIKit_Image_Path]){
        [fileManager createDirectoryAtPath:TUIKit_Image_Path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if(![fileManager fileExistsAtPath:TUIKit_Video_Path]){
        [fileManager createDirectoryAtPath:TUIKit_Video_Path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if(![fileManager fileExistsAtPath:TUIKit_Voice_Path]){
        [fileManager createDirectoryAtPath:TUIKit_Voice_Path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if(![fileManager fileExistsAtPath:TUIKit_File_Path]){
        [fileManager createDirectoryAtPath:TUIKit_File_Path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if(![fileManager fileExistsAtPath:TUIKit_DB_Path]){
        [fileManager createDirectoryAtPath:TUIKit_DB_Path withIntermediateDirectories:YES attributes:nil error:nil];
    }
}
- (void)configNotification{
    [[V2TIMManager sharedInstance] addConversationListener:self];
    [TUICore registerEvent:TUICore_TUIConversationNotify subKey:TUICore_TUIConversationNotify_SelectConversationSubKey object:self];
    [TUICore registerEvent:TUICore_TUIConversationNotify subKey:TUICore_TUIConversationNotify_ClearConversationUIHistorySubKey object:self];
    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(onFriendInfoChanged:) name:@"FriendInfoChangedNotification" object:nil];

    [TUICore registerEvent:TUICore_TUIContactNotify subKey:TUICore_TUIContactNotify_UpdateConversationBackgroundImageSubKey object:self];
    [TUICore registerEvent:TUICore_TUIGroupNotify subKey:TUICore_TUIGroupNotify_UpdateConversationBackgroundImageSubKey object:self];
    [TUICore registerEvent:TUICore_TUIPollNotify subKey:TUICore_TUIPollNotify_PollCreatedSubKey object:self];
    //拨打视频时，调创建房间ID的接口
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createRealCallRoomId:) name:@"TUICallCreateRoomId" object:nil];
    //查看患者档案
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkPatientDetailAction) name:@"CheckPatientRecord" object:nil];
    //查看最新病情概览
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkDiseaseOverviewAction) name:@"CheckDiseaseOverview" object:nil];
    //查看医生详情
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkDoctorDetail:) name:@"CheckDoctorDetail" object:nil];
    //视频咨询订单详情
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkVideoOrderDetail:) name:@"CheckOrderDetail" object:nil];
    //慢病服务详情
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkServiceDetail:) name:@"CheckServiceDetail" object:nil];
    //去做评估
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkEvaluationDetail:) name:@"CheckEvaluationDetail" object:nil];
    //查看医嘱详情
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkDoctorAdviceDetail:) name:@"CheckDoctorAdviceDetail" object:nil];
    
}

- (void)createMessageController{
    TUIMessageController *controller = [[TUIMessageController alloc] init];
    controller.isMsgNeedReadReceipt = [TUIChatConfig defaultConfig].msgNeedReadReceipt;
    controller.hightlightKeyword = self.highlightKeyword;
    controller.locateMessage = self.locateMessage;
    [controller setConversation:self.conversationData];
    controller.delegate = self;
    self.messageController = controller;

    CGFloat bottomMargin = (_appointment_id && _appointment_id.length>0 && ![_appointment_id containsString:@"999999999-"])?viewPix(44):0;
    
    self.messageController.view.frame = CGRectMake(0,  topMargin, viewWidth,viewHeight - TTextView_Height - bottomMargin - Bottom_SafeHeight - topMargin);
    [self addChildViewController:self.messageController];
    [self.view addSubview:self.messageController.view];
    [self.messageController didMoveToParentViewController:self];
}

-(void)createSubView{
    if(_appointment_id && _appointment_id.length>0 && ![_appointment_id containsString:@"999999999-"]){
        [self.view addSubview:self.patientNavigation];
        [self.view addSubview:self.extendTimeView];
        [[UIApplication sharedApplication].keyWindow addSubview:self.timeView];
        if(self.conversationData.groupID && self.conversationData.groupID.length>0){
            self.patientNavigation.teamBtn.hidden = NO;
        }else{
            self.patientNavigation.teamBtn.hidden = YES;
        }
    }else{
        [self.view addSubview:self.teamNavigation];
        self.teamNavigation.title = self.conversationData.title;
        if(self.conversationData.groupID && self.conversationData.groupID.length>0){
            self.teamNavigation.teamBtn.hidden = NO;
        }else{
            self.teamNavigation.teamBtn.hidden = YES;
        }
    }
    [self addChildViewController:self.inputController];
    [self.view addSubview:self.inputController.view];
}



-(TUIChatDataProvider *)dataProvider{
    if(!_dataProvider){
        _dataProvider = [[TUIChatDataProvider alloc] init];
        _dataProvider.forwardDelegate = self;
    }
    return _dataProvider;
}

-(TUIChatMediaDataProvider *)mediaProvider{
    if (_mediaProvider == nil) {
        _mediaProvider = [[TUIChatMediaDataProvider alloc] init];
        _mediaProvider.presentViewController = self;
        _mediaProvider.listener = self;
    }
    return _mediaProvider;
}

-(TUIInputController *)inputController{
    if(!_inputController){
        _inputController = [[TUIInputController alloc] init];
        _inputController.showItemView = (_appointment_id && _appointment_id.length>0 && ![_appointment_id containsString:@"999999999-"])?YES:NO;
        CGFloat height = (_appointment_id && _appointment_id.length>0 && ![_appointment_id containsString:@"999999999-"])?(TTextView_Height +viewPix(40) + Bottom_SafeHeight):(TTextView_Height + Bottom_SafeHeight);
        _inputController.view.frame = CGRectMake(0, viewHeight - height, viewWidth, height);
        _inputController.view.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        _inputController.delegate = self;
        @weakify(self)
        [RACObserve(self, moreMenus) subscribeNext:^(NSArray *x) {
            @strongify(self)
            [self.inputController.moreView setData:x];
        }];
    }
    return _inputController;
}


-(LGChatPatientNavigation *)patientNavigation{
    if(!_patientNavigation){
        _patientNavigation = [[LGChatPatientNavigation alloc]initWithFrame:CGRectMake(0, 0, Screen_W, topBarHeight+viewPix(44))];
        [_patientNavigation.backBtn addTarget:self action:@selector(backButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [_patientNavigation.patientBtn addTarget:self action:@selector(checkPatientDetailAction) forControlEvents:UIControlEventTouchUpInside];
        [_patientNavigation.teamBtn addTarget:self action:@selector(checkTeamMemberAction) forControlEvents:UIControlEventTouchUpInside];
        [_patientNavigation.statusBtn addTarget:self action:@selector(changeConsultStatusAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _patientNavigation;
}

-(LGChatTeamNavigation *)teamNavigation{
    if(!_teamNavigation){
        _teamNavigation = [[LGChatTeamNavigation alloc] initWithFrame:CGRectMake(0, 0, Screen_W, topBarHeight)];
        [_teamNavigation.backBtn addTarget:self action:@selector(backButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [_teamNavigation.patientBtn addTarget:self action:@selector(checkPatientDetailAction) forControlEvents:UIControlEventTouchUpInside];
        [_teamNavigation.teamBtn addTarget:self action:@selector(checkTeamMemberAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _teamNavigation;
}

-(UIImageView *)extendTimeView{
    if(!_extendTimeView){
        _extendTimeView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"聊天咨询-延长时长"]];
        _extendTimeView.frame = CGRectMake(Screen_W-viewPix(166), kMaxY(self.patientNavigation.frame)-viewPix(5), viewPix(156), viewPix(160));
        _extendTimeView.userInteractionEnabled = YES;
        _extendTimeView.hidden = YES;
        [_extendTimeView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(extendTimeViewAction:)]];
    }
    return _extendTimeView;
}

-(LGExtendTimeView *)timeView{
    if(!_timeView){
        _timeView = [[LGExtendTimeView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
        _timeView.delegate = self;
        _timeView.hidden = YES;
    }
    return _timeView;
}

-(LGPatientDeleteView *)deleteView{
    if(!_deleteView){
        _deleteView = [[LGPatientDeleteView alloc] initWithFrame:CGRectMake(0, viewHeight-((TTextView_Height + Bottom_SafeHeight/2.0)), Screen_W, TTextView_Height + Bottom_SafeHeight/2.0)];
        _deleteView.hidden = YES;
    }
    return _deleteView;
}

-(LGReceptionView *)receptView{
    if(!_receptView){
        _receptView = [[LGReceptionView alloc] initWithFrame:self.inputController.view.frame];
        _receptView.hidden = YES;
        [_receptView.receptBtn addTarget:self action:@selector(receptConsultAction) forControlEvents:UIControlEventTouchUpInside];
        [_receptView.refuseBtn addTarget:self action:@selector(refuseConsultAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _receptView;
}

-(NSTimer *)timer{
    if(!_timer){
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
    }
    return _timer;
}

@end
